package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.poi.StringUtils;
import com.bwie.utils.R;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.User;
import com.bwie.mapper.UserMapper;
import com.bwie.service.UserService;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: yiang
 * @Date:  2025/10/11 08:58
 * @Description: 
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    UserMapper userMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public R getLogin(User user) {

        //查询user
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //查询账号并判断
        if(StringUtils.isNotEmpty(user.getUserName())){
            wrapper.lambda().eq(User::getUserName,user.getUserName());
        }
        //查询手机号，并判断格式
        if(StringUtils.isNotEmpty(user.getUserPhone())){
            //调用正则表达式
            Pattern compile = Pattern.compile("^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$");
            //测试
            Matcher matcher = compile.matcher(user.getUserPhone());
            //返回值
            boolean matches = matcher.matches();
            if(matches){
                wrapper.lambda().eq(User::getUserPhone,user.getUserPhone());
            }else{
                return R.ERROR(500,"手机号格式错误");
            }
        }

        //查询邮箱
        if(StringUtils.isNotEmpty(user.getUserEmail())){
            wrapper.lambda().eq(User::getUserEmail,user.getUserEmail());
        }

        User one = userMapper.selectOne(wrapper);

        if(one==null){
            return R.ERROR(500,"账号不存在");
        }

        Pattern compile = Pattern.compile("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{6,}$");
        Matcher matcher = compile.matcher(user.getUserPwd());
        boolean matches = matcher.matches();
        if(matches){
            if(!one.getUserPwd().equals(user.getUserPwd())){
                return R.ERROR(500,"密码错误");
            }
        }else{
            return R.ERROR(500,"格式错误");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").claim("userId", one.getUserId()).compact();
        redisTemplate.opsForValue().set("token"+one.getUserId(),token,15, TimeUnit.MINUTES);

        one.setToken(token);

        return R.OK(one);
    }
}
